<template>
  <div class="iframeEditPositionBox">
    <div class="positionInfo">
      <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }" class="formStyle">
        <a-card :title="$t('candidateApplication.position_info')" :bordered="false" style="width: 100%">
          <div v-for="(item, index) in templateMatching[0] ? templateMatching[0].fields : []" :key="index" :class="item.type === 'RICH_TEXTAREA' ? 'positionInfoList RichTextareaStyle' : 'positionInfoList'">
            <div :class="item.type === 'RICH_TEXTAREA' ? 'labelBoxStyle labelRichTextareaStyle' : 'labelBoxStyle'"><span :style="{ opacity: item.required ? 1 : 0, color: 'red', marginRight: '10px' }">*</span>{{ item.displayName }}</div>
            <div :class="item.type === 'RICH_TEXTAREA' ? 'valueBoxStyle valueRichTextareaStyle' : 'valueBoxStyle'">
              <a-form-item class="formLabel" :class="item.key === 'number' ? 'editTheNumber' : ''">
                <component v-decorator="[item.key, {rules: [{ required: item.required, message: $t('common.pleaseEnter') + item.displayName }]}]"
                  :placeholders="item.displayName" :is="item.type" :url='item.url' :values='item.values' :keys='item.key' :isDisabled="positionOperationType !== 'add' && (item.key === 'enterpriseId' || item.key === 'weChatPositionType' || item.key === 'hrSiteTypes') ? true : item.readonly" style="width:96%;margin-left:2%;" @changePositionEdit='changePositionEdit' :unlimitedNumberValue="unlimitedNumberValue" locationMode="multiple" @change="onChangeFormValue($event, item)"
                >
                </component>
              </a-form-item>
              <span v-if="item.key === 'number'" class="unlimitedNumber">
                <a-checkbox v-model="unlimitedNumberValue" @change="unlimitedNumberFn" :disabled="item.readonly">{{$t('common.unlimited_people')}}</a-checkbox>
              </span>
            </div>
          </div>
        </a-card>
        <a-card :title="$t('position_management.company_info')" :bordered="false" style="width: 100%;margin-top:10px;" v-if="templateMatching[1] && templateMatching[1].fields">
          <div v-for="(item, index) in templateMatching[1] ? templateMatching[1].fields : []" :key="index" :class="item.type === 'RICH_TEXTAREA' ? 'positionInfoList RichTextareaStyle' : 'positionInfoList'">
            <div :class="item.type === 'RICH_TEXTAREA' ? 'labelBoxStyle labelRichTextareaStyle' : 'labelBoxStyle'">{{ item.displayName }}</div>
            <div :class="item.type === 'RICH_TEXTAREA' ? 'valueBoxStyle valueRichTextareaStyle' : 'valueBoxStyle'">
              <a-form-item class="formLabel">
                <component v-decorator="[item.key, {rules: [{ required: item.required, message: $t('common.pleaseEnter') + item.displayName }]}]" :isReadOnlyPage="false"
                  :placeholders="item.displayName" :is="item.type" :url='item.url' :values='item.values' :keys='item.key' :isDisabled="positionOperationType !== 'add' && (item.key === 'enterpriseId' || item.key === 'weChatPositionType' || item.key === 'hrSiteTypes') ? true : item.readonly" style="width:96%;margin-left:2%;" locationMode="multiple" @change="onChangeFormValue($event, item)"
                >
                </component>
              </a-form-item>
            </div>
          </div>
        </a-card>
      </a-form>
    </div>
  </div>
</template>

<script>
import { positionPositionTemplate, positionPositionDetail, modifyOrAddPosition } from '@/api/position'
import TEXT_FIELD from '@/components/formComponents/TextField/TextField'
import SELECT from '@/components/formComponents/Select/Select'
import INT from '@/components/formComponents/Int/Int'
import DEPARTMENT from '@/components/formComponents/Department/Department'
import JOB_TYPE from '@/components/formComponents/JobType/JobType'
import LOCATION from '@/components/formComponents/Location/city'
import RADIO_GROUP from '@/components/formComponents/RadioGroup/RadioGroup'
import RICH_TEXTAREA from '@/components/formComponents/RichTextarea/RichTextarea'
import DATE from '@/components/formComponents/Date/Date'
import CHECKBOX_GROUP from '@/components/formComponents/Checkbox/Checkbox'
let timer = null
export default {
  name: 'iframeEditPosition',
  components: { TEXT_FIELD, SELECT, INT, DEPARTMENT, JOB_TYPE, LOCATION, RADIO_GROUP, RICH_TEXTAREA, DATE, CHECKBOX_GROUP },
  data () {
    return {
      positionId: '',
      recruitmentTypeId: '',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      templateMatching: [],
      positionData: {},
      positionOperationType: '',
      unlimitedNumberValue: false
    }
  },
  watch: {
    $route: {
      handler (val, oldVal) {
        console.log(val, oldVal)
        if (val.params.pid !== oldVal.params.pid) {
          this.positionId = this.$route.params.pid
          this.recruitmentTypeId = this.$route.params.recruitmentTypeId
          this.getPositionPositionTemplate()
        }
      },
      deep: true
    }
  },
  created () {
    // this.$route.params.pid(职位id) / this.$route.params.recruitmentTypeId(职位招聘类型) 必传
    if (this.$route.params.type === 'addPosition') {
      this.recruitmentTypeId = 'SOCIALRECRUITMENT'
      this.positionOperationType = 'add'
      this.positionData = {}
      this.templateMatching = []
    } else if (this.$route.params.type) {
      this.positionId = this.$route.params.type
    } else {
      this.positionId = this.$route.params.pid
    }
    this.recruitmentTypeId = this.$route.params.recruitmentTypeId || ''
    this.getPositionPositionTemplate()
  },
  mounted () {
    window.addEventListener('message', this.handleMessage)
  },
  methods: {
    unlimitedNumberFn (e) { // 如果职位上的招聘人数为不限，则给后台传入-1
      this.unlimitedNumberValue = e.target.checked
      this.form.setFieldsValue({
        'number': -1
      })
    },
    getPositionPositionTemplate () {
      positionPositionTemplate({
        recruitmentType: this.recruitmentTypeId
      }).then(res => {
        if (res.code === 200) {
          let arr = []
          res.data.fieldGroups[0].fields.forEach(element => {
            if (element.visible) {
              arr.push(element)
            }
          })
          res.data.fieldGroups[0].fields = arr
          this.templateMatching = res.data.fieldGroups
          console.log(this.templateMatching)
          if (this.positionOperationType === 'add') {
            setTimeout(() => {
              this.$nextTick(function () {
                this.form.setFieldsValue({ 'weChatPositionType': { id: 'SOCIALRECRUITMENT', name: this.$t('position_management.SOCIALRECRUITMENT') } })
              })
              this.templateMatching[0].fields.forEach(ele => {
                if (ele.key === 'hrSiteTypes' && ele.values.length === 1) { // 默认选中第一个
                  this.$nextTick(function () {
                    this.form.setFieldsValue({ 'hrSiteTypes': [{ id: ele.values[0].id, name: ele.values[0].name }] })
                  })
                }
              })
            }, 500)
          } else {
            this.$nextTick(() => {
              this.fetchPositionById()
            })
          }
        }
      })
    },
    fetchPositionById () {
      positionPositionDetail({
        positionId: this.positionId
      }).then(res => {
        if (res.code === 200) {
          this.positionData = res.data
          console.log(this.positionData)
          if (Number(this.positionData.number) === -1 || Number(this.positionData.number) === 0) { // 如果对接过来的职位招聘人数为0或者-1  那就转换成不限
            this.unlimitedNumberValue = true
          }
          this.$nextTick(function () {
            setTimeout(() => {
              if (this.positionData && this.positionData.multiLocation && this.positionData.multiLocation.length) {
                this.positionData['location'] = this.positionData.multiLocation
              }
              this.form.setFieldsValue(this.positionData)
            }, 500)
          })
        }
      })
    },
    changePositionEdit (html, text, quill) {
      if (html === '<div><br></div>') {
        html = ''
      }
      this.form.setFieldsValue({
        'detail': html
      })
    },
    handleMessage () {
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.positionData.id) {
            values.id = this.positionData.id
            values.enterpriseId = this.positionData.enterpriseId
          }
          if (values.location && Object.prototype.toString.call(values.location) === '[object Array]') {
            let str = ''
            values.location.forEach(ele => {
              str += (ele.parentName ? (ele.parentName + '-') : '') + ele.name + ','
            })
            this.$set(values, 'baseProvinceCity', str.substr(0, str.length - 1)) // 字符串类型 北京-东城区，北京-朝阳区
            this.$set(values, 'multiLocation', values.location) // 数组类型 [{name: '东城区', id: 0, parentName: '北京'}, {name: '朝阳区', id: 1, parentName: '北京'}]
            values.location = {}
          }
          this.debounce(values, 500)
        } else {
          window.parent.postMessage('warning', '*')
        }
      })
    },
    debounce (data, time) {
      if (timer) clearTimeout(timer)
      let callNow = !timer
      timer = setTimeout(() => {
        timer = null
      }, time)
      if (callNow) {
        modifyOrAddPosition(data).then(res => {
          if (res.code === 200) {
            window.parent.postMessage('success', '*')
            // this.fetchPositionById()
          } else {
            window.parent.postMessage('failed', '*')
          }
        }).catch(error => {
          if (error) {
            window.parent.postMessage('failed', '*')
          }
        })
      }
    },
    onChangeFormValue (value, item) {
      this.$nextTick(() => {
        if (item.type === 'LOCATION' && item.key === 'location') {
          if (Object.prototype.toString.call(value) === '[object Array]') {
            let arr = []
            value.forEach(ele => {
              arr = [...arr, ...this.recursionChildren(ele)]
            })
            arr = filterByProperty(arr, 'id')
            this.form.setFieldsValue({
              'location': arr
            })
          }
        }
      })
    },
    recursionChildren (ele) { // 递归出所有含有children的值传出去
      let arr = []
      if (ele.children && ele.children.length) {
        ele.children.forEach(element => {
          if (element.children && element.children.length) {
            this.recursionChildren(element)
          } else {
            arr.push(element)
          }
        })
      } else {
        arr.push(ele)
      }
      return arr
    }
  }
}
function filterByProperty (objArr, property) { // 根据唯一属性去重
  let obj = {}
  return objArr.reduce((acc, cur) => {
    if (cur) {
      obj[cur[property]] ? obj[cur[property]] = false : obj[cur[property]] = true && acc.push(cur)
      return acc
    }
  }, [])
}
</script>

<style lang="stylus" scoped>
@import '../../styles/var.styl'
.iframeEditPositionBox
  width 100%
  .valueRichTextareaStyle
    :global(.ant-form-item)
      margin-top 32px
    :global(.ant-form-item-control)
      line-height 0
  .positionInfo
    width 100%
    .formLabel:global(.ant-form-item)
      padding-top 20px
      margin-bottom 0px
    .formLabel :global(.ant-col-19)
      width 100%
    .editTheNumber
      width 80%
      display inline-block
    .unlimitedNumber
      display inline-block
      margin-top 30px
      float right
    .positionInfoList
      width 100%
      height 80px
      border-bottom 1px solid #e2e2e2
      &:first-child
        margin-top 1px
      .labelBoxStyle
        width 25%
        float left
        background #fafafa
        height 100%
        line-height 80px
        padding-left 20px
      .valueBoxStyle
        width 74%
        float left
        background #fff
    .RichTextareaStyle
      height auto
      display inline-block
      position relative
      .labelRichTextareaStyle
        position absolute
      .valueRichTextareaStyle
        margin-left 25%
  .positionSetting
    width 94%
    margin-left 6%
    background #fff
    border 1px solid #e6e6e6
    border-radius 7px
    box-shadow 0 0 28px 2px #e8e8e8
    .publishInfo
      line-height 30px
  .formStyle .positionInfo :global(.ant-card-body)
    padding 0px
  .formStyle :global(.ant-input-disabled)
    color #555!important
    background #fafafa!important
  .formStyle :global(.ant-input-number-disabled)
    color #555!important
    background #fafafa!important
  .formStyle :global(.ant-radio-button-wrapper-disabled)
    color #555!important
    background #fafafa!important
  .formStyle :global(.ant-form-explain)
    padding-left 10px
</style>
